<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
function htmlEntities(str) {
	return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}
var socket = io.connect('http://192.168.137.218:8080');

	// on connection to server, ask for user's name with an anonymous callback
	socket.on('connect', function(){
		// call the server-side function 'adduser' and send one parameter (value of prompt)
		socket.emit('adduser', prompt("What's your name?"));
	});

	// listener, whenever the server emits 'updatechat', this updates the chat body
	socket.on('updatechat', function (username, data) {
		var mess = htmlEntities(data);
		$('#conversation').append('<b>'+username + ':</b> ' + mess + '<br>');
		$('#conversation').scrollTop($('#conversation')[0].scrollHeight);
	});

	// listener, whenever the server emits 'updaterooms', this updates the room the client is in
	socket.on('updaterooms', function(rooms, current_room) {
		$('#selectRooms').empty();
		$.each(rooms, function(key, value) {
			$('#selectRooms').append('<option value="'+ value +'">'+ value +'</option>');
		});
	});

	function switchRoom(room){
		socket.emit('switchRoom', room);
	}
	
	// on load of page
	$(function(){
		// when the client clicks SEND
		var sendMessage = false;
		var timeSend = new Date();
		$('#datasend').click( function() {
			var message = $('#data').val();
			$('#data').val('');
			// tell server to execute 'sendchat' and send along one parameter
			if(message != ""){
				if(sendMessage == true){
					if(timeSend.getTime() <= ((new Date()).getTime() - 1000)){
						socket.emit('sendchat', message);
						timeSend = new Date();
						console.log(timeSend.getTime());
					}
					else{
						mess = "You can't send more than 1 message per second";
						$('#conversation').append('<b class="pseudo">SERVER:</b> <span class="message">' + mess + '</span><br>');
						$('#conversation').scrollTop($('#conversation')[0].scrollHeight);
					}
				}

				if(sendMessage == false){
					socket.emit('sendchat', message);
					sendMessage = true;
					timeSend = new Date();
					console.log(timeSend.getTime());
					
				}
			}
		});

		// when the client hits ENTER on their keyboard
		$('#data').keypress(function(e) {
			if(e.which == 13) {
				//$(this).blur();
				$('#datasend').click();
			}
		});

		$("#selectRooms").change(function() {
			var room = $("#selectRooms").val();
			switchRoom(room);
		});
	});
</script>
<div>
	<b>ROOMS</b>
	<select id="selectRooms" name="rooms">
	</select>
</div>
<div id="chat">
	<div id="conversation"></div>
	<input id="data" style="width:200px;" />
	<input type="button" id="datasend" value="send" />
</div>
<style type="text/css">

#conversation{
	width: 100%;
	height: 500px;
	overflow: auto;
	white-space: nowrap;
	overflow-y:scroll-y; 
}
</style>

